package logic

import (
	"2210a/commod/models/mysql"
	"2210a/commod/models/redisinit"
	"2210a/commod/pkg"
	"context"
	"fmt"

	"2210a/commod/commodrpc/commodrpc"
	"2210a/commod/commodrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginUserLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginUserLogic {
	return &LoginUserLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginUserLogic) LoginUser(in *commodrpc.LoginUserRequest) (*commodrpc.LoginUserResponse, error) {
	// todo: add your logic here and delete this line
	var users mysql.Users

	mysql.Db.Debug().Where("username = ?", in.Username).Find(&users)
	if users.ID == 0 {
		return nil, fmt.Errorf("账号未注册，请重新输入")
	}
	get := redisinit.ClientRedis.Get("sendSmslogin" + in.Username)
	if get.Val() != in.SendSms {
		return nil, fmt.Errorf("获取短信验证码错误")
	}
	if users.Password != pkg.Md5(in.Password) {
		return nil, fmt.Errorf("密码不一致，请重新输入")
	}
	//redisinit.ClientRedis.Del("sendSmslogin" + in.Username)
	return &commodrpc.LoginUserResponse{Id: int64(users.ID)}, nil
}
